//
//  HPCache.m
//  LockTest
//
//  Created by ZhangBo on 2018/12/2.
//  Copyright © 2018 ZhangBo. All rights reserved.
//

#import "HPCache.h"

@interface HPCache ()
@property(nonatomic, readonly) NSMutableDictionary *cacheObjects;
@property(nonatomic, readonly) dispatch_queue_t queue;
@end

@implementation HPCache

- (instancetype)init {
    if (self = [super init]) {
        _cacheObjects = [NSMutableDictionary new];
        _queue = dispatch_queue_create("kCacheQueueName", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

+ (HPCache *)sharedInstance {
    static HPCache *instance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        instance = [[HPCache alloc] init];
    });
    return instance;
}

- (id)objectForKey:(id)key {
    __block id rv = nil;
    dispatch_sync(self.queue, ^{
        rv = self.cacheObjects[key];
    });
    return rv;
}

- (void)setObject:(id)object forKey:(id)key {
    dispatch_barrier_async(self.queue, ^{
        self.cacheObjects[key] = object;
    });
}


- (void)clear {
    dispatch_sync(self.queue, ^{
        [self.cacheObjects removeAllObjects];
    });
}

- (id)removeObjectForKey:(id <NSCopying>)key {
    __block id rv = nil;

    dispatch_sync(self.queue, ^{
        rv = self.cacheObjects[key];
        [self.cacheObjects removeObjectForKey:key];
    });
    return rv;
}

@end
